package com.jinlejia.erp.ui.message;

import android.os.Bundle;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.jinlejia.erp.R;
import com.jinlejia.erp.base.ApiConfig;
import com.jinlejia.erp.base.MapCallBack;
import com.jinlejia.erp.databinding.ActivityMessageContentBinding;
import com.jinlejia.erp.ui.common.ProgressDialog;
import com.jinlejia.erp.utils.DataFilter;
import com.lab.Lab;
import com.weight.CustomToast;
import com.zhy.http.okhttp.OkHttpUtils;

import org.simple.eventbus.EventBus;

import java.util.Map;

import okhttp3.Call;
import okhttp3.MediaType;

/**
 * 消息内容（Activity）
 */

public class MessageContentActivity extends AppCompatActivity {

    private String url , link ,resourceCode;
    private boolean isCollect;
    private JSONObject jsonObject = new JSONObject();
    private ProgressDialog progressDialog;

    private ActivityMessageContentBinding binding;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this,R.layout.activity_message_content);
        binding.backBtn.setOnClickListener(this::onClick);
        binding.favorites.setOnClickListener(this::onClick);
        binding.clickCheck.setOnClickListener(this::onClick);

        progressDialog = new ProgressDialog(this,"请稍等...");
        url = ApiConfig.MESSAGE_DETAILS.concat( getIntent().getStringExtra("objectId")).concat("/type.").concat(getIntent().getStringExtra("time"));
    }

    @Override
    protected void onStart() {
        super.onStart();
        getData();
    }


    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.back_btn:
                finish();
                break;
            case R.id.favorites:
                jsonObject.put("objectId",getIntent().getStringExtra("objectId"));
                jsonObject.put("type",getIntent().getStringExtra("time"));
                Collect();
                isCollect = !isCollect ;
                if (isCollect){
                    binding.favorites.setTag(0);
                    binding.favorites.setBackgroundResource(R.mipmap.ic_has_collect);
                }else {
                    binding.favorites.setTag(1);
                    binding.favorites.setBackgroundResource(R.mipmap.ic_collect);
                }
                EventBus.getDefault().post("s","TAG_ISCOLLECT_MESSAGE");
                break;
            case R.id.click_check:
                Lab.mainPushProtocol().sendMainPush(this,resourceCode,link);
                break;
        }
    }

    /**
     * 获取数据
     */
    private void getData(){
        OkHttpUtils
                .get()
                .url(url)
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        if (DataFilter.filter(MessageContentActivity.this, response,null)) {
                            Map<String,Object> map = JSON.parseObject(response.get("data").toString(),new TypeReference<Map<String, Object>>(){});
                            if (map.containsKey("content") && !TextUtils.isEmpty(map.get("content").toString()))
                                binding.content.setText(Html.fromHtml(map.get("content").toString()));
                            link = (!TextUtils.isEmpty(map.get("link").toString())? map.get("link").toString():"");
                            if (map.containsKey("isCollect")){
                                isCollect = (boolean) map.get("isCollect");
                                if (isCollect){
                                    binding.favorites.setBackgroundResource(R.mipmap.ic_has_collect);
                                }else {
                                    binding.favorites.setBackgroundResource(R.mipmap.ic_collect);
                                }
                            }
                            resourceCode = !TextUtils.isEmpty(map.get("resourceCode").toString())? map.get("resourceCode").toString():"";
                            if ( (!TextUtils.isEmpty(link) && !TextUtils.isEmpty(resourceCode)) || link.indexOf("http")==0  ){
                                binding.clickCheck.setVisibility(View.VISIBLE);
                                binding.clickCheck.setText("点击查看");
                            }else if( link.equals("myCommissions") ){
                                //跳转分成列表
                                binding.clickCheck.setVisibility(View.VISIBLE);
                                binding.clickCheck.setText("点击查看");
                            }else if( link.equals("shsfollowprice")||link.equals("rentfollowprice")){
                                //跳转跟进价格页面
                                binding.clickCheck.setVisibility(View.VISIBLE);
                                binding.clickCheck.setText("点击查看");
                            }
                        }
                    }
                });
    }

    /**
     * 收藏 （重复调用此接口 如果是已收藏则 取消收藏）
     */
    private void Collect(){
        progressDialog.show();
        OkHttpUtils
                .postString()
                .url(ApiConfig.MESSAGE_COLLECTION)
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .content(jsonObject.toString())
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        e.printStackTrace();
                        if (null != progressDialog && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        if (null != progressDialog && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }
                        if (DataFilter.filter(MessageContentActivity.this, response, null)) {
                            if (binding.favorites.getTag().toString().equals("0")){
                                CustomToast.showToast(MessageContentActivity.this,"已收藏",2000);
                                binding.favorites.setBackgroundResource(R.mipmap.ic_has_collect);
                            }else {
                                CustomToast.showToast(MessageContentActivity.this,"取消收藏",2000);
                                binding.favorites.setBackgroundResource(R.mipmap.ic_collect);
                            }
                        }
                    }
                });
    }

    @Override
    protected void onDestroy() {
        if (null != progressDialog && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
        super.onDestroy();
        EventBus.getDefault().post("","TAG_READ_NOTIFY");
    }
}
